import re

from django.conf import settings
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class RbacMiddleWare(MiddlewareMixin):
    """
    权限校验中间件
    """
    def process_request(self, request):
        current_url = request.path_info

        for valid_url in settings.VALID_URL_LIST:
            regx = '^%s$' % valid_url
            if re.match(regx, current_url):

                return None

        permission_dict = request.session.get(settings.MOBILEDJ_PERMISSION_SESSION_KEY)
        if not permission_dict:
            return HttpResponse('未获取到权限信息，请登录')

        url_record = [{'title': '首页', 'url': '#'}]
        # 此处代码进行判断
        for url in settings.NO_PERMISSION_LIST:
            regx = '^%s$' % url
            if re.match(regx, request.path_info):
                # 需要登录，但无需权限校验
                request.current_selected_permission = 0
                request.breadcrumb = url_record
                return None
        flag = False
        for item in permission_dict.values():

            regx = '^%s$' % item['url']
            if re.match(regx, current_url):
                flag = True
                if item['pid']:
                    url_record.extend([
                        {'title': item['p_title'], 'url': item['p_url']},
                        {'title': item['title'], 'url': item['url'], 'class': 'active'}
                    ])
                else:
                    url_record.extend([
                        {'title': item['title'], 'url': item['url'], 'class': 'active'},
                    ])
                request.breadcrumb = url_record
                request.current_selected_permission = item['pid'] or item['id']
                break

        if not flag:
            return HttpResponse('无访问权限')

        return None
